package com.share.shareplatform.shareuser.controller;

import com.share.shareplatform.pojo.User;
import com.share.shareplatform.pojo.exception.LogicException;
import com.share.shareplatform.shareuser.service.UserService;
import com.share.shareplatform.util.AuthorityUtil;
import com.share.shareplatform.util.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation(value="用户注册",notes = "必需字段:username,password")
    @PostMapping("register")
    @PermitAll
    public Result register(@RequestBody(required = false ) @Validated User user) throws LogicException {

        if(user.getUsername()==null||user.getPassword()==null){
            throw new LogicException("账号和密码不能为空");
        }
        User inUser=userService.findOneByUsername(user.getUsername());
        if(inUser!=null){
            return Result.getInstance(505,"用户已存在");
        }

        User.setInit(user);
        Long aLong = userService.addOne(user);
        if(aLong>0){
            return Result.getInstance(200,"注册成功");
        }
        return Result.getInstance(505,"注册失败，请重试");
    }

    /*
    *
    * 该登录只是提供一个接口，实际登录业务并不会进入该方法中
    *
    * */
    @ApiOperation(value="用户登录",notes = "必需字段：username,password\n额外说明：登录成功后会返回一个Authorization的字符串作为登录验证")
    @PostMapping("login")
    public void login(@RequestBody(required = false ) User user){
        
    }


    //客户端提供user的信息即可
    @ApiOperation(value="用户信息修改",notes = "可选字段:name,phone\n前提:用户已经登录")
    //secured只对角色控制有效
    //@Secured("ROLE_admin")
    @PreAuthorize("hasAuthority('userUpdate')")
    @PutMapping
    public Result updateOne(@RequestBody @Validated User user,HttpServletRequest request) throws Exception {
        //普通用户需要权限认证
        if (!AuthorityUtil.hasAuthorityUtil("ROLE_admin")) {
            //获取用户jwt中的id
            Long authorityId =AuthorityUtil.getUserId();
            if(authorityId!=user.getId()){
                throw new Exception("权限不足");
            }
        }
        if(user.getId()==null){
            throw new Exception("id不能为空");
        }

        userService.updateBaseOne(user);
        return Result.getInstance(200,"success");
    }

    @ApiOperation(value="用户删除")
    //@Secured("userDelete")
    @PreAuthorize("hasAuthority('userSuper')")
    @DeleteMapping("/{id}")
    public Result deleteOneById(@PathVariable("id") Long id) throws Exception {

        Integer integer = userService.deleteOneById(id);
        if(integer==0){
            return Result.getInstance(505,"删除失败");
        }
        return Result.getInstance(200,"success");
    }

    @ApiOperation(value="用户批量删除",notes = "其中ids为 'id-id-id' 这种类型的字符串")
    @DeleteMapping("/all/{ids}")
    @PreAuthorize("hasAuthority('userSuper')")
    public Result deleteAllByIds(@PathVariable("ids") String ids){
        String[] stringIds=ids.split("-");
        ArrayList<Long> arrayList=new ArrayList<>();
        for(String id:stringIds){
            arrayList.add(Long.parseLong(id));
        }
        Integer integer = userService.deleteAllByIds(arrayList.toArray(new Long[arrayList.size()]));
        if(integer==0){
            return Result.getInstance(505,"删除失败");
        }
        return Result.getInstance(200,"删除了 "+integer+" 条数据");
    }

    @ApiOperation(value="按username查询用户")
    @GetMapping("/username/{username}")
    @PreAuthorize("hasAuthority('userSuper')")
    public Result findOneByUsername(@PathVariable("username") String username){
        if(username==null||username.trim().equals("")){
            return Result.getInstance(505,"账号不能为空").put("user",null);
        }
        User user=userService.findOneByUsername(username);
        return Result.getInstance(200,"success").put("user",user);
    }

    @ApiOperation(value="获取用户个人信息",notes = "前提：用户已登录")
    @GetMapping
    @PreAuthorize("hasAuthority('userFind')")
    public Result findOneByToken(){
        Long userId = AuthorityUtil.getUserId();
        User user = userService.findOneById(userId);
        if(user!=null)
            return Result.getInstance(200,"success").put("user",user);
        else{
            return Result.getInstance(505,"登录失效，请先登录").put("user",null);
        }
    }

    @ApiOperation(value="用户密码修改",notes = "注意：提交格式为application/x-www-form-urlencoded，而不是application/json\n前提：用户已经登录")
    @PutMapping("/password")
    @PreAuthorize("hasAuthority('userUpdate')")
    public Result updatePassword(@NotBlank(message = "旧密码不能为空")  String oldPassword,
                                 @NotBlank(message = "新密码不能为空")
                                 @Pattern(regexp = "^[A-Za-z0-9]{3,15}$",message = "新密码只能是数字或字母，且长度为3-20") String newPassword){

        Long authorityId =AuthorityUtil.getUserId();
        //如果是普通用户需要验证
        if (!AuthorityUtil.hasAuthorityUtil("ROLE_admin")) {
            //获取用户jwt中的id
            User oldUser=userService.findOneById(authorityId);
            if(oldUser==null){
                return Result.getInstance(505,"用户已被注销");
            }
            if(!oldPassword.equals(oldUser.getPassword())){
                return Result.getInstance(505,"原密码不正确");
            }
        }

        //保证只修改密码
        User newUser=new User();
        newUser.setPassword(newPassword);
        newUser.setId(authorityId);
        userService.updateOne(newUser);

        return Result.getInstance(200,"修改成功");
    }

    @ApiOperation(value="获取所有用户信息，分页查询" ,notes = "必须字段：pageIndex（第几页），pageSize(每页大小)")
    /*@ApiImplicitParams({
            @ApiImplicitParam(name = "pageIndex", value = "第几页", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页的大小", required = true, dataType = "Integer")
    })*/
    @GetMapping("/page/{pageIndex}/{pageSize}")
    @PreAuthorize("hasAuthority('userSuper')")
    public Result getUserPage(@PathVariable("pageIndex") Integer pageIndex, @PathVariable("pageSize") Integer pageSize){
        //从第一页开始
        pageIndex--;
        if(pageIndex<0||pageSize<0){
            return Result.getInstance(505,"页码有误").put("list",null);
        }
        List<User> list=userService.findPage(pageIndex,pageSize);
        return Result.getInstance(200,"success").put("list",list);
    }

    @ApiOperation(value="根据用户ids查找多个用户，只查询基本信息")
    @PermitAll
    @GetMapping("/all/safe/{ids}")
    public Result findAllSafeByIds(@PathVariable("ids") String ids){
        String[] split = ids.split("-");
        Long[] longs=new Long[split.length];
        for(int i=0;i< split.length;i++){
            longs[i]=Long.parseLong(split[i]);
        }
        List<User> list = userService.findAllSafeByIds(longs);

        return Result.getInstance(200,"success").put("list",list);
    }

    @ApiOperation(value="根据用户id查找用户，只查询基本信息")
    @GetMapping("/safe/{id}")
    @PermitAll
    public Result findOneSafeById( @PathVariable("id") Long id){

        User user = userService.findOneSafeById(id);
        return Result.getInstance(200,"success").put("user",user);
    }


    @ApiOperation(value="根据用户id查找用户")
    @PermitAll
    //@PreAuthorize("hasAuthority('userSuper')")
    @GetMapping("/{id}")

    public Result findOneById(@PathVariable("id") Long id) throws Exception {
        User user = userService.findOneById(id);
        return Result.getInstance(200,"success").put("user",user);
    }

    @PermitAll
    @GetMapping("/map/{ids}")
    public Result findAllSafeByIdsAsMap(@PathVariable("ids") String ids) {

        String[] stringIds=ids.split("-");
        ArrayList<Long> arrayList=new ArrayList<>();
        for(String id:stringIds){
            arrayList.add(Long.parseLong(id));
        }
        Map<Long, User> map = userService.findAllSafeByIdsAsMap(arrayList);

        return Result.getInstance(200,"success").put("map",map);
    }

    @GetMapping("/test/user")
    @PermitAll
    public Result test(@RequestBody User user){
        userService.addOne(user);
        return Result.getInstance(200,"success");
    }

}
